import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Input, Select, Button, Table, Modal, Pagination } from 'antd';
import { DEFAULT_PAGE_SIZE, DEFAULT_INVALID_STATE, DEFAULT_VALID_STATE } from '@/constants';
import styles from './index.less';

import Edit from './edit';

const { Content } = Layout;
const { confirm } = Modal;
const { Option } = Select;

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'unit';
    const { global } = props;
    const { isAdmin, currentUnit = {} } = global;
    this.state = {
      unitName: currentUnit.unit_name,
      unitId: currentUnit.id,
      selectedRows: [],
      loading: false,
      mohu: "",
    }
  }

  componentDidMount() {
    const { unitId } = this.state;
    this.props.dispatch({
      type: `${this.modularName}/queryDataTitle`,
      payload: {
        unit_id: unitId,
        pageNo: 1,
        pageSize: DEFAULT_PAGE_SIZE
      }
    });
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增职务', editData: {} }
    })
  }

  editBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑职务', editData: record }
    })
  }

  stopBtnClick = (record) => {
    confirm({
      title: '是否确删除该职务?',
      onOk: () => {
        const { dispatch, modular } = this.props;
        const { pageNo, pageSize } = modular;

        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/deleteDataTitle`,
          payload: {
            id: record.id,
            is_expired: 1,
            callback: () => {

            }
          }
        });
      },
      onCancel() { },
    });
  }

  stopBtnClickPl = (record) => {
    confirm({
      title: '是否确删除所选职务?',
      onOk: () => {
        const { dispatch, modular } = this.props;
        const { selectedRows, unitId } = this.state;
        let tiaojian = [];
        selectedRows && selectedRows.length && selectedRows.map(item => {
          tiaojian.push({ id: item, unit_id: unitId })
        })
        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/updateIsExpiredListTitle`,
          payload: {
            list: tiaojian
          }
        });
      },
      onCancel() { },
    });
  }

  searchBtnClick = () => {
    const { mohu = "", unitId } = this.state;
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/queryDataTitleByMohu`,
      payload: {
        unit_id: unitId,
        duty_name: mohu,
        pageNo: 1,
        pageSize: DEFAULT_PAGE_SIZE
      }
    });
  }

  onChange = (pageNo, pageSize) => {
    const { mohu = "", unitId } = this.state;
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/queryDataTitleByMohu`,
      payload: {
        unit_id: unitId,
        duty_name: mohu,
        pageNo: pageNo,
        pageSize: DEFAULT_PAGE_SIZE
      }
    })
  }

  onOk = () => {
    const { unitId } = this.state;
    const { dispatch, form, modular } = this.props;
    const { editData = {}, pageNo, pageSize, visible } = modular;
    form.validateFields((err, values) => {
      if (!err) {
        if (visible == "新增职务") {
          dispatch({
            type: `${this.modularName}/saveDutyTitle`,
            payload: {
              duty_name: values.duty_name,
              unit_id: unitId
            }
          });
        } else if (visible == "编辑职务") {
          dispatch({
            type: `${this.modularName}/updateDutyTitle`,
            payload: {
              duty_name: values.duty_name,
              id: editData.id
            }
          });
        }
      }
    });
  }

  onSelectChange = selectedRows => {
    this.setState({ selectedRows });
  };

  render() {
    const { unitId, selectedRows = [], unitName } = this.state;
    const { dispatch, form, loading, global, modular } = this.props;
    const { } = global;
    const { data, pageNo = 1, pageSize = DEFAULT_PAGE_SIZE, count = 0, rowKey, visible, editData = {} } = modular;
    const rowSelection = {
      selectedRows,
      onChange: this.onSelectChange,
    };

    const columns = [
      {
        title: '单位名称',
        dataIndex: 'unit_name',
        ellipsis: true,
        width: 250,
        render: (text, record) => {
          return <span>{unitName}</span>
        }
      },
      {
        title: '职务名称',
        dataIndex: 'duty_name',
        ellipsis: true,
        width: 350
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
              <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>删除</span>
            </div>
          );
        }
      }
    ];

    return (
      <Layout className={styles.basic_layout_wrapper} style={{ ...this.props.style }}>
        <div className={styles.conditions_wrapper}>
          <Input placeholder='职务名称' style={{ width: 240, marginRight: 16 }} onChange={e => this.setState({ mohu: e.target.value })} />
          <Button icon='search' type='primary' onClick={this.searchBtnClick}>搜索</Button>
        </div>
        <Content className={styles.conditions_wrapper} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            <div>
              <Button icon='plus' type='primary' style={{ width: 110, marginRight: 16, marginBottom: 16 }} onClick={this.appendBtnClick}>新增职务</Button>
              {
                <Button icon='delete' type='danger' style={{ marginBottom: 16 }} onClick={this.stopBtnClickPl.bind(this, selectedRows)}>批量删除{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
              }
            </div>
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={columns}
                dataSource={data}
                loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                pagination={false}
                rowKey={rowKey}
                rowSelection={rowSelection}
                scroll={{ x: true }}
              />
            </Content>
            <div style={{ marginTop: 16 }}>
              <Pagination
                current={pageNo}
                pageSize={pageSize}
                total={count}
                showQuickJumper
                showSizeChanger={true}
                showTotal={(count, range) => `共有 ${count} 条数据`}
                onChange={this.onChange}
              />
            </div>
          </Layout>
        </Content>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={600}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            })
          }}
        >
          <Edit form={form} data={editData} unitName={unitName} />
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, global, unit }) => ({ loading, global, modular: unit }))(Form.create()(Index));